<?php


namespace app\admin\system\logic;


use app\admin\system\service\AdminService;
use app\common\logic\BaseLogic;
use app\common\service\ConfigService;
use app\common\service\PasswordService;
use app\model\SysAdmin;
use common\service\JwtService;
use core\exception\BadException;
use core\utils\Time;
use RobThree\Auth\TwoFactorAuth;
use Tinywan\Captcha\Captcha;
use yzh52521\JwtAuth\facade\JwtAuth;

class LoginLogic extends BaseLogic
{
    function login($username, $password, $ext)
    {

        $token = $ext['token'] ?? "";
        $code = $ext['code'] ?? "";
        $google_authenticator_code = $ext['google_authenticator_code'] ?? "";

        $config = ConfigService::getConfig("LOGIN_CONFIG");
        //图文验证码
        if ($config && $config['enable'] === 'on') {
            if (!$code) {
                throw new BadException("验证码错误");
            }
            if (false === Captcha::check($code, $token)) {
                throw new BadException("验证码错误");
            }
        }

        $user = SysAdmin::where([
            'username|mobile' => $username
        ])->field(['id', 'nickname', 'password', 'salt', 'status', 'google_auth_secret'])->find();
        if (!$user) {
            throw new BadException("账号密码错误");
        }
        //谷歌动态码验证
        if ($user->google_auth_secret && $config && $config['google_authenticator_enable'] === 'on') {
            if (!$google_authenticator_code) {
                throw new BadException("账号绑定了谷歌验证器,请填写谷歌动态码");
            }
            $auth = new TwoFactorAuth();
            if (!$auth->verifyCode($user->google_auth_secret, strval($google_authenticator_code))) {
                throw new BadException("谷歌动态码错误");
            }
        }
        if (!PasswordService::checkPassword($password, $user['password'], $user['salt'])) {
            throw new BadException("账号密码错误");
        }
        if ($user['status'] != 0) {
            throw new BadException("账号已经被禁用");
        }

        $user->ip = request()->getRealIp();
        $user->login_time = Time::now();
        $user->save();
        $config = JwtAuth::getConfig('admin');
        $token = JwtService::generateToken($user['id'], 'admin');
        $roles = AdminService::getRoles($user->id);

        return [
            "tokenName" => "Authorization",
            'tokenValue' => $token,
            'token_type' => $config->getType(),
            'expires_in' => $config->getExpires(),
            'refresh_in' => $config->getRefreshTTL(),
            'userInfo' => [
                'dashboard' => 0,
                'role' => array_column($roles, 'name'),
                'userId' => $user->id,
                'userName' => $user->nickname,
            ]
        ];
    }
}